package com.mingqijia.gassafety.authority.security.facade;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mingqijia.gassafety.authority.api.req.company.CompanyThirdPartyDTO;
import com.mingqijia.gassafety.authority.api.req.company.CreateCompanyReqDTO;
import com.mingqijia.gassafety.authority.api.req.company.QueryCompanyReqDTO;
import com.mingqijia.gassafety.authority.api.req.company.UpdateCompanyReqDTO;
import com.mingqijia.gassafety.authority.api.resp.company.CompanyLiteRespDTO;
import com.mingqijia.gassafety.authority.api.resp.company.CompanyRespDTO;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.api.web.facade.CompanyManageFacade;
import com.mingqijia.gassafety.authority.dal.command.CreateCompanyCommand;
import com.mingqijia.gassafety.authority.dal.command.RemoveCompanyCommand;
import com.mingqijia.gassafety.authority.dal.command.UpdateCompanyCommand;
import com.mingqijia.gassafety.authority.dal.handler.CompanyTranslator;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.authority.dal.provider.CompanyProvider;
import com.mingqijia.gassafety.authority.domain.adapter.BenAdapter;
import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.enums.RunningState;
import com.mingqijia.gassafety.shared.facade.BaseFacade;
import com.mingqijia.gassafety.shared.handler.GlobalAuthenticationException;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * REST接口
 * @author Damon S.
 * @version v0.2
 * @date 2021-06-19
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class CompanyManageFacadeImpl extends BaseFacade implements CompanyManageFacade {

    private final CompanyProvider provider;
    private final ConfigureHolder holder;
    private final CompanyTranslator translator;
    private final BenAdapter benAdapter;


    @Override
    public PageUtil<CompanyLiteRespDTO> findAll() {
        List<CompanyLiteRespDTO> records = provider.buildHierarchy();
        return PageUtil.init(
                new Page<>(Constants.LONG_ONE, Constants.LONG_1_KILO, records.size()),
                records
        );
    }

    @Override
    public List<CompanyRespDTO> findVccOrgs() {
        return null;
    }

    @Override
    public PageUtil<CompanyRespDTO> find(@Valid QueryCompanyReqDTO req) {
        Page<CompanyEntry> results = provider.find(translator.toCommand(req));
        List<CompanyRespDTO> response = translator.toRespDTO(results.getRecords());

        if (CollectionUtils.isEmpty(response)) {
            return new PageUtil<>();
        }
        Map<String, DictionaryItemRespDTO> orgAttrItems =
                holder.getDictionaryInMap(Constants.CACHE_KEY_ORG_NATURE);
        Map<String, DictionaryItemRespDTO> orgTypeItems =
                holder.getDictionaryInMap(Constants.CACHE_KEY_ORG_TYPE);

        response.forEach(item -> {
            if (Objects.equals(item.getType(), Constants.DICTIONARY_PLATFORM)) {
                item.setTypeCn(item.getName());
                item.setNatureCn(ObjectUtils.isEmpty(item.getName())
                        ? Constants.STR_STRIKETHROUGH : item.getName()
                );
            } else {
                item.setTypeCn(orgTypeItems.get(item.getType()).getName());
                if (ObjectUtils.isEmpty(item.getNature())) {
                    item.setNatureCn(Constants.STR_STRIKETHROUGH);
                } else {
                    item.setNatureCn(orgAttrItems.get(item.getNature()).getName());
                }
            }
        });
        return PageUtil.init(results, response);
    }

    @Override
    public CompanyThirdPartyDTO find(String spId) {
        // TODO: 暂缓
        return null;
    }

    @Override
    public void create(CompanyThirdPartyDTO req) {
        // TODO: 暂缓
    }

    @Override
    public String create(CreateCompanyReqDTO req) {
        this.validateWorkingSpace4Platform();
        CreateCompanyCommand command = translator.toCommand(req);
        String createdSpId;

        // 历史问题的处理方案:在本安部门表插入对应数据
        try {
            createdSpId = provider.create(command);
            benAdapter.createCompanyDepart(createdSpId, command.getName());
        } catch (Exception e) {
            log.error("在本安插入新建企业失败", e);
            throw new GlobalAuthenticationException("新建企业失败-100101");
        }
        return createdSpId;
    }

    @Override
    public void update(UpdateCompanyReqDTO req) {
        this.validateWorkingSpace4Platform();
        if (!provider.update(translator.toCommand(req))) {
            throw new GlobalAuthenticationException("操作失败");
        }
    }

    @Override
    public void remove(String[] spId) {
        this.validateWorkingSpace4Platform();
        RemoveCompanyCommand command = RemoveCompanyCommand.builder()
                .id(Arrays.asList(spId)).build();
        if (!provider.remove(command)) {
            throw new GlobalAuthenticationException("操作失败");
        }
    }

    @Override
    public void switchCompany(String spId, Integer state) {
        this.validateWorkingSpace4Platform();
        if (state > Constants.INT_ONE || state < Constants.INT_ZERO) {
            throw new GlobalAuthenticationException("请求参数不合法");
        }
        UpdateCompanyCommand command = UpdateCompanyCommand.builder()
                .id(spId).state(RunningState.parse(state)).build();
        if (!provider.update(command)) {
            throw new GlobalAuthenticationException("操作失败");
        }
    }
}
